<template>
  <div class="roles-page">
    <div class="page-header">
      <h2>角色管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 角色列表 -->
    <el-card>
      <el-table :data="roles" v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <!-- 编辑按钮 -->
            <el-button size="small" type="primary" @click="editRole(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>

            <!-- 权限管理按钮（状态感知） -->
            <el-button
              size="small"
              :type="getPermissionButtonType(row)"
              @click="handlePermissionManage(row)"
            >
              <el-icon><Setting /></el-icon>
              {{ getPermissionButtonText(row) }}
            </el-button>

            <!-- 更多操作下拉菜单 -->
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button size="small">
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="clone">
                    <el-icon><CopyDocument /></el-icon>
                    复制角色
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="delete"
                  >
                    <el-icon><Delete /></el-icon>
                    删除角色
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="editingRole ? '编辑角色' : '添加角色'"
      width="600px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRole" :loading="saving">
          {{ editingRole ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限管理对话框 -->
    <RolePermissionDialog
      v-model="showPermissionDialog"
      :role="selectedRole"
      @saved="handlePermissionSaved"
    />



    <!-- 复制角色对话框 -->
    <el-dialog
      v-model="showCloneDialog"
      title="复制角色"
      width="500px"
    >
      <el-form
        ref="cloneFormRef"
        :model="cloneForm"
        label-width="100px"
        :rules="cloneFormRules"
      >
        <el-form-item label="原角色" prop="originalRole">
          <el-input v-model="cloneForm.originalRole" disabled />
        </el-form-item>
        <el-form-item label="新角色名" prop="name">
          <el-input v-model="cloneForm.name" placeholder="请输入新角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="cloneForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showCloneDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmClone" :loading="cloning">
          确认复制
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Edit, ArrowDown, Setting, CopyDocument, Delete
} from '@element-plus/icons-vue'
import { userManagementAPI } from '@/api/userManagement'
import RolePermissionDialog from '@/components/RolePermissionDialog.vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const cloning = ref(false)
const roles = ref([])
const showAddDialog = ref(false)
const editingRole = ref(null)

// 新增的对话框状态
const showPermissionDialog = ref(false)
const showCloneDialog = ref(false)
const showDeleteWarning = ref(false)
const selectedRole = ref(null)

// 角色表单
const roleForm = reactive({
  name: '',
  description: ''
})

// 复制角色表单
const cloneForm = reactive({
  originalRole: '',
  name: '',
  description: ''
})

// 表单验证规则
const cloneFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 模板引用
const roleFormRef = ref(null)
const cloneFormRef = ref(null)

// 方法
const loadRoles = async () => {
  loading.value = true
  try {
    const response = await userManagementAPI.getRoles()
    roles.value = response.results || response
  } catch (error) {
    console.error('加载角色失败:', error)
    ElMessage.error('加载角色失败')
  } finally {
    loading.value = false
  }
}

const editRole = (role) => {
  editingRole.value = role
  roleForm.name = role.name
  roleForm.description = role.description
  showAddDialog.value = true
}

const saveRole = async () => {
  if (!roleFormRef.value) return

  try {
    saving.value = true

    if (editingRole.value) {
      await userManagementAPI.updateRole(editingRole.value.id, roleForm)
      ElMessage.success('角色更新成功')
    } else {
      await userManagementAPI.createRole(roleForm)
      ElMessage.success('角色创建成功')
    }

    showAddDialog.value = false
    resetForm()
    loadRoles()
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败')
  } finally {
    saving.value = false
  }
}

const deleteRole = async (role) => {
  try {
    // 先进行安全检查
    const safetyCheck = await userManagementAPI.checkRoleDeletionSafety(role.id)

    // 移除系统角色检查，允许删除所有角色
    // if (safetyCheck.is_system_role) {
    //   ElMessage.error(safetyCheck.warning_message)
    //   return
    // }

    if (safetyCheck.has_associated_users) {
      // 显示关联用户信息，让用户决定是否继续
      selectedRole.value = role
      showDeleteWarning.value = true
      showUsersDialog.value = true
      return
    }

    // 没有关联用户，直接确认删除
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await userManagementAPI.deleteRole(role.id)
    ElMessage.success('角色删除成功')
    loadRoles()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }
}

// 新增的操作方法
const handlePermissionManage = (role) => {
  selectedRole.value = role
  showPermissionDialog.value = true
}

// 状态感知的权限按钮
const getPermissionButtonType = (role) => {
  // 这里可以根据角色的权限配置状态返回不同类型
  // 暂时先用success，后续会根据实际权限状态动态判断
  return 'success'
}

const getPermissionButtonText = (role) => {
  // 这里可以根据角色的权限配置状态返回不同文本
  // 暂时先返回基础文本，后续会根据实际权限状态动态判断
  return '权限管理'
}

const handleMoreAction = async (command, role) => {
  selectedRole.value = role

  switch (command) {
    case 'clone':
      cloneForm.originalRole = role.name
      cloneForm.name = `${role.name}_副本`
      cloneForm.description = `${role.description} (副本)`
      showCloneDialog.value = true
      break
    case 'delete':
      await deleteRole(role)
      break
  }
}

const confirmClone = async () => {
  if (!cloneFormRef.value) return

  try {
    await cloneFormRef.value.validate()
    cloning.value = true

    await userManagementAPI.cloneRole(selectedRole.value.id, {
      name: cloneForm.name,
      description: cloneForm.description
    })

    ElMessage.success('角色复制成功')
    showCloneDialog.value = false
    resetCloneForm()
    loadRoles()
  } catch (error) {
    console.error('复制角色失败:', error)
    ElMessage.error('复制角色失败')
  } finally {
    cloning.value = false
  }
}

const handleDeleteConfirmed = async (role) => {
  try {
    await userManagementAPI.deleteRole(role.id)
    ElMessage.success('角色删除成功')
    loadRoles()
  } catch (error) {
    console.error('删除角色失败:', error)
    ElMessage.error('删除角色失败')
  }
}

const handlePermissionSaved = () => {
  ElMessage.success('权限配置已保存')
  loadRoles() // 重新加载角色列表
}

const handleViewUser = (user) => {
  // 可以跳转到用户详情页面或显示用户信息
  ElMessage.info(`查看用户: ${user.username}`)
}

// 移除系统角色检查，允许删除所有角色

const resetCloneForm = () => {
  cloneForm.originalRole = ''
  cloneForm.name = ''
  cloneForm.description = ''
}

const resetForm = () => {
  roleForm.name = ''
  roleForm.description = ''
  editingRole.value = null
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadRoles()
})
</script>

<style scoped>
.roles-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

/* 操作列样式优化 */
:deep(.el-table__cell) {
  padding: 8px 0;
}

/* 操作列容器样式 */
:deep(.el-table__cell:last-child .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  white-space: nowrap;
}

/* 图标按钮样式 */
:deep(.el-button.is-circle) {
  width: 32px;
  height: 32px;
  flex-shrink: 0;
}

/* 下拉菜单容器样式 */
:deep(.el-dropdown) {
  display: inline-flex;
  align-items: center;
}

/* 操作列按钮悬停效果 */
:deep(.el-button.is-circle:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.2s ease;
}

/* 操作列居中对齐 */
:deep(.el-table .el-table__cell:last-child) {
  text-align: center;
}

/* 下拉菜单样式优化 */
:deep(.el-dropdown-menu__item.is-disabled) {
  color: #c0c4cc;
  cursor: not-allowed;
}

/* Tooltip 样式 */
:deep(.el-tooltip__trigger) {
  display: inline-block;
}

/* 下拉菜单样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 14px;
}

/* 系统角色标识 */
.system-role-tag {
  margin-left: 8px;
}

/* 对话框样式优化 */
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}
</style>
